package com.hbnu.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chendikai
 * @date 2024-11-13 上午 10:10
 */
public class CookieUtils {

    public static void addCookie(String cookieName, int time,
                                 HttpServletRequest request, HttpServletResponse response,
                                 String stuCode, String password) {

        Cookie cookie = getCookieByCookieName(cookieName, request);

        if (cookie != null) {  // 如果cookie已存在，则更新cookie的值
            cookie.setValue(stuCode + "#" + password);
        } else { // 如果cookie不存在，则创建cookie，并将数据存入cookie中
            cookie = new Cookie(cookieName, stuCode + "#" + password);
        }

        cookie.setMaxAge(time);  // 设置cookie存活时间
        cookie.setPath(request.getContextPath());   // 设置cookie范围

        response.addCookie(cookie);  // 将cookie返回给浏览器
    }

    public static Cookie getCookieByCookieName(String cookieName, HttpServletRequest request) {

        Cookie[] cookies = request.getCookies();  // 获取浏览器中的cookie
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {  // 根据cookieName获取cookie
                    return cookie;
                }
            }
        }
        return null;
    }
}
